package com.wiseMen.wechat.user;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.sword.wechat4j.exception.WeChatException;
import org.sword.wechat4j.user.LanguageType;
import org.sword.wechat4j.user.User;
import org.sword.wechat4j.user.UserManager;

import com.ibm.icu.util.Calendar;
import com.wiseMen.core.dao.EntityDao;
import com.wiseMen.core.dao.PageRequestInfo;

/**
 * 微信用户
 * @author 吴人龙
 */
@Service("wechat_userservice")
public class WechatUserService {

	@Autowired
    private EntityDao entityDao;
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	public List<WechatUserEntity> listpage(PageRequestInfo pageRequestInfo,WechatUserEntity entity) {
        List<WechatUserEntity> listpage=new ArrayList<WechatUserEntity>();
        listpage=this.entityDao.selectByPage(WechatUserEntity.class, entity, "selectWechatUserListPage", pageRequestInfo);
        return listpage;
    }
	
	/**
	 * 对指定用户设置备注名
	 * @param openId
	 * @param remarkName 新的备注名，长度必须小于30字符 
	 * @throws WeChatException 
	 */
	public void setRemarkName(String openId,String remarkName) throws WeChatException{
		UserManager manager = new UserManager();
		manager.updateRemark(openId, remarkName);
		WechatUserEntity entity = new WechatUserEntity();
		entity.setId(openId);
		entity.setRemarkName(remarkName);
		this.entityDao.saveSelective(entity);
	}
	
	/**
	 * 同步单个微信用户基本信息
	 * @param openId
	 */
	public void syncUserInfo(String openId){
		UserManager manager = new UserManager();
		User user = manager.getUserInfo(openId, LanguageType.zh_CN);
		WechatUserEntity entity = new WechatUserEntity(user);
		this.save(entity);
	}
	
	/**
	 * 同步多个微信用户基本信息
	 * @param openIds
	 */
	public void syncUserInfos(String[] openIds){
		for(String openId : openIds){
			this.syncUserInfo(openId);
		}
	}
	
	/**
	 * 同步全部微信用户基本信息（如果关注者过多，建议在服务器闲时操作）
	 */
	public void syncAllUser(){
		UserManager manager = new UserManager();
		List<String> list = manager.allSubscriber();
		List<User> userList = manager.getManyUserInfo(list, LanguageType.zh_CN);
		this.unsubscribe();
		for(User user : userList){
			WechatUserEntity entity = new WechatUserEntity(user);
			this.save(entity);
		}
	}
	
	/**
	 * 设置全部用关注状态为0
	 */
	private void unsubscribe(){
		this.jdbcTemplate.update("UPDATE WC_USER SET SUBSCRIBE=0");
	}
	
	/**
	 * 保存/更新
	 * @param entity
	 */
	private void save(WechatUserEntity entity){
		if(StringUtils.isNotBlank(entity.getId())){
			entity.setSyncTime(Calendar.getInstance().getTime());
			if(isExists(entity.getId())){
				this.entityDao.saveSelective(entity);
			}else{
				this.entityDao.insert(entity);
			}
		}
	}
	
	/**
	 * 根据OPENID判断是否已存在数据库
	 * @param openId 微信唯一ID
	 * @return boolean true:已存在  false:不存在
	 */
	public boolean isExists(String openId){
		int count = this.jdbcTemplate.queryForObject("SELECT COUNT(*) FROM WC_USER WHERE ID=?", new String[]{openId}, Integer.class);
		return count>0;
	}
}
